package org.example.secondkill.controller;

import org.example.secondkill.domain.Goods;
import org.example.secondkill.domain.User;
import org.example.secondkill.domain.vo.GoodsDetailVO;
import org.example.secondkill.redis.GoodsKey;
import org.example.secondkill.redis.RedisService;
import org.example.secondkill.response.BaseResponse;
import org.example.secondkill.service.IGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private RedisService redisService;

    /**
     * 获得所有秒杀商品列表
     */
    @GetMapping("/list")
    @ResponseBody
    public List<Goods> list() {
        // 查询商品列表
        return goodsService.getAllGoods();
    }

    /**
     * 查询待秒杀商品详情
     */
    @RequestMapping(value = "/detail/{goodsId}")
    @ResponseBody
    public BaseResponse<GoodsDetailVO> goodsDetail(@PathVariable("goodsId") long goodsId, User userVO) {
        // 渲染
        // todo: 商品详情是否需要存 redis ???
        GoodsDetailVO goodsDetailVO = goodsService.getGoodsDetailVOByGoodsId(goodsId);
        goodsDetailVO.setUser(userVO);
        return BaseResponse.success(goodsDetailVO);
    }

    @Scheduled(fixedRate = 20000)
    public void schedule() {
        List<Goods> goodsList = goodsService.getAllGoods();
        if (goodsList == null) {
            return;
        }

        // 库存写回数据库
        for (Goods goods : goodsList) {
            int stock = redisService.get(GoodsKey.getGoodsStock, "" + goods.getId(), Integer.class);
            if (stock < 0) {
                stock = 0;
            }
            goods.setGoodsStock(stock);
        }
        goodsService.updateGoods(goodsList);
    }
}
